package com.zing.service.impl;

import com.zing.dto.GoodsSalesDTO;
import com.zing.entity.Orders;
import com.zing.mapper.OrderMapper;
import com.zing.mapper.UserMapper;
import com.zing.service.ReporterService;
import com.zing.service.WorkspaceService;
import com.zing.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReporterServiceImpl implements ReporterService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    // 营业额统计
    public TurnoverReportVO getTurnover(LocalDate begin, LocalDate end) {
        ArrayList<LocalDate> dateList = new ArrayList<>(); // 日期数据数组
        ArrayList<Double> turnoverList = new ArrayList<>(); // 营业额数组
        dateList.add(begin);
        while(!begin.equals(end)){
             begin = begin.plusDays(1); // plusDays 创建并返回一个新的
            dateList.add(begin);
        }
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            // 营业额查询
            Map<Object, Object> map = new HashMap<>();
            map.put("status", Orders.CONFIRMED);
            map.put("begin", beginTime);
            map.put("end", endTime);
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null? 0.0 : turnover;
            turnoverList.add(turnover);
        }

        //返回数据
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))  // StringUtils.join 数组转字符串
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    // 用户数据量统计
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        List<Integer> daysUserCountList = new ArrayList<>(); //单日用户数
        List<Integer> totalUserCountList = new ArrayList<>(); //截止end时间点,总用户数

        // 日期构造
        dateList.add(begin);
        while(!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Integer addUser = getUserCount(beginTime, endTime);
            Integer totalUser = getUserCount(null, endTime);

            daysUserCountList.add(addUser);
            totalUserCountList.add(totalUser);
        }

        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(daysUserCountList,","))
                .totalUserList(StringUtils.join(totalUserCountList,","))
                .build();
    }

    // 订单数据量统计
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        List<Integer> daysOrderCountList  = new ArrayList<>(); //单日订单数
        List<Integer> daysValidOrderCountList  = new ArrayList<>(); //单日有效订单数
        Integer totalOrderCount = 0; // 时间区间内的总订单数
        Integer totalValidOrderCount = 0; // 时间区间内的总有效订单数
        Double totalOrderCompletionRate = 0.0; // 时间区间内订单完成率

        // 日期构造
        dateList.add(begin);
        while(!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer orderCount = getOrderCount(beginTime, endTime, null);
            Integer validOrderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);

            daysOrderCountList.add(orderCount);
            daysValidOrderCountList.add(validOrderCount);
        }

        totalOrderCount = daysOrderCountList.stream().reduce(0, (a, b) -> a + b);
        totalValidOrderCount = daysValidOrderCountList.stream().reduce(Integer::sum).get();
        if(totalOrderCount != 0) totalOrderCompletionRate = totalValidOrderCount/(double) totalOrderCount;

        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(daysOrderCountList, ","))
                .validOrderCountList(StringUtils.join(daysValidOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(totalValidOrderCount)
                .orderCompletionRate(totalOrderCompletionRate)
                .build();
    }

    //时间段内销量前十统计
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> list = orderMapper.getSalesTop10(beginTime, endTime);

        String nameList = StringUtils.join(list.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList()),",");
        String numberList = StringUtils.join(list.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList()),",");

        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    // 导出运营数据表
    public void exportOperateForm(HttpServletResponse response) {
        LocalDate beginDate = LocalDate.now().minusDays(30);
        LocalDate endDate = LocalDate.now().minusDays(1);
        // 查询概览运营数据
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(beginDate,LocalTime.MIN), LocalDateTime.of(endDate, LocalTime.MAX));
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营报表模板.xlsx");

        try {
            // 基于模板文件创建一个新的Excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);

            // 获得Excel文件中的Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue(beginDate + "至" + endDate); //设置具体格子内容

            // 第4行
            XSSFRow row = sheet.getRow(3);
            // 单元格单元格赋值
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());

            // 第5行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());

            Integer rowAddNum = 0;
            for (int i = 29; i >= 0; i--) { // 倒序
                LocalDate date = beginDate.plusDays(i);
                // 明细数据
                businessData = workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                rowAddNum++;
                row = sheet.getRow(6 + rowAddNum);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            //通过输出流将文件返回给浏览器,响应的是一个.xlsx文件, 浏览器默认直接下载
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            //out.flush(); // flush()方法用于刷新输出流。它会将输出流中的缓冲区数据立即发送给客户端，确保数据及时传输
            //out.close() 方法用于关闭输出流。它会释放与输出流相关的资源，并确保所有数据都已经发送给客户端。
            out.close(); // 调用该方法会自动调用flush()方法，因此在关闭输出流之前，会先刷新缓冲区数据。关闭输出流后，将无法再继续使用该输出流进行写入操作
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // method 根据时间区间, 查询订单数量
    private Integer getOrderCount(LocalDateTime beginTime, LocalDateTime endTime, Integer status) {
        Map map = new HashMap();
        map.put("status", status);
        map.put("begin",beginTime);
        map.put("end", endTime);
        return orderMapper.countByMap(map);
    }

    // method 根据时间区间, 查询用户数量
    private Integer getUserCount(LocalDateTime beginTime, LocalDateTime endTime) {
        Map map = new HashMap();
        map.put("begin",beginTime);
        map.put("end", endTime);
        return userMapper.countByMap(map);
    }
}
